import * as types from '../mutation-types'
import {getCollect} from 'api/user-info'
import {deCollect} from 'api/topics'
import moment from 'moment'

moment.locale('zh-cn')

const state = {
  myCollect: []
}

const getters = {
  myCollect: state => state.myCollect
}

const actions = {
  // api获取我的收藏
  getMyCollect({commit}, {loginname}) {
    return getCollect(loginname).then((res) => {
      if (res.success === false) {
        return res
      } else {
        res.data.forEach((item) => {
          item.create_at = moment(item.create_at).startOf().fromNow()
          delete item.content
        })
        commit(types.SET_MY_COLLECT, res.data)
        return res
      }
    })
  },
  // 取消收藏
  cancelCollect({commit}, {id, token}) {
    return deCollect(id, token).then((res) => {
      if (res.success === false) {
        return res
      } else {
        let array = state.myCollect.slice()
        array.forEach((item, index) => {
          if (item.id === id) {
            array.splice(index, 1)
          }
        })
        commit(types.SET_MY_COLLECT, array)
        return res
      }
    })
  }
}

const mutations = {
  [types.SET_MY_COLLECT](state, list) {
    state.myCollect = list
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
